#!/usr/bin/python
# -*- coding: latin1 -*-
"""

    Name: writer.py

    Author: Enrico Bortolazzi - Veia Progetti s.r.l.

    Comment: musicXML writer

    Version: 1.0

    Date: Fri Aug 17, 2007

------------------------------------------------------------------------

Copyright (c) 2007, Veia Progetti s.r.l. - http://www.veia.it

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the distribution.

    Neither name of Veia Progetti s.r.l. nor the name of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
import os
from StringIO import StringIO
from lxml import etree
import codecs
import xml.sax.saxutils as sxu
import _musicXML

def _writeElement(element):
    if not element: return ''

    if element._name[0] == '_':
        tag_open = ''
    else:
        attrs = []
        for a in element._attrs:
            v = getattr(element, '%s' % _musicXML.name_mangle(a))
            if v != None:
                attrs.append(a + '=' + sxu.quoteattr(unicode(v)))
        if attrs:
            tag_open = '<%s %s>' % (element._name, ' '.join(attrs))
        else:
            tag_open = '<%s>' % element._name

    if hasattr(element, '_content'):
        content = [sxu.escape(unicode(element._content))]  #??
    else:
        content = []
        for e in element:
            content.append(_writeElement(e))
    content = ''.join(content)

    if content:
        if element._name[0] == '_':
            tag_close = ''
        else:
            tag_close = '</%s>' % element._name

        return tag_open + content + tag_close

    else:
        tag_open = tag_open[:-1] + '/>'
        return tag_open


def write(filename_or_stream, score, version='2.0', xslpath=''):
    if not version in ['1.0', '1.1', '2.0']:
        raise ValueError, 'version %s is not handled' % version
    if hasattr(filename_or_stream, 'write'):
        fstream = filename_or_stream
    elif isinstance(filename_or_stream, basestring):
        fstream = codecs.open(filename_or_stream, encoding='utf-8', mode='w')
    else:
        raise ValueError, 'parameter %s is not a stream or filename' % str(filename_or_stream)

    xml_encoding = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'
    xml_doctype = '<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 2.0 Partwise//EN\" \"http://www.musicxml.org/dtds/partwise.dtd\">'
    buf = '%s\n%s\n%s' %(xml_encoding, xml_doctype, _writeElement(score))

    if version in ['1.0', '1.1']:
        tmpstream = StringIO(buf.encode('utf-8'))
        doc_tree = etree.parse(tmpstream)
        if version == '1.1':
            xslt_doc = etree.parse(os.path.normpath('%s/to11.xsl' % xslpath))
        elif version == '1.0':
            xslt_doc = etree.parse(os.path.normpath('%s/to10.xsl' % xslpath))
        transform = etree.XSLT(xslt_doc)
        res_tree = transform(doc_tree)
        fstream.write(str(res_tree))
    else:
        fstream.write(buf)
